package com.cf.controller;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections4.map.LinkedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cf.entity.ErpQtnAttachEntity;
import com.cf.entity.ErpQtnCostItemEntity;
import com.cf.entity.ErpQtnProductCostEntity;
import com.cf.entity.ErpQtnProductEntity;
import com.cf.entity.ErpQuotationEntity;
import com.cf.entity.SysUserEntity;
import com.cf.mapper.ErpQtnAttachEntityMapper;
import com.cf.mapper.ErpQtnCostItemEntityMapper;
import com.cf.mapper.ErpQtnProductCostEntityMapper;
import com.cf.mapper.ErpQtnProductEntityMapper;
import com.cf.mapper.ErpQuotationEntityMapper;
import com.cf.mapper.SysUserEntityMapper;
import com.cf.service.ErpQtnProdCostService;
import com.cf.utils.R;
import com.cf.utils.ShiroUtils;
import com.cf.utils.UploadFile;
import com.cf.utils.annotation.SysLog;

import cn.hutool.core.bean.BeanUtil;

@RestController
@RequestMapping("/erp/quotation")

public class ErpQuotationController {

	@Autowired
	private ErpQtnProdCostService erpQtnProdCostService;

	@Resource
	private ErpQuotationEntityMapper erpQuotationEntityMapper;
	@Resource
	private ErpQtnProductEntityMapper erpQtnProductEntityMapper;
	@Resource
	private ErpQtnAttachEntityMapper erpQtnAttachEntityMapper;
	@Resource
	private ErpQtnProductCostEntityMapper erpQtnProductCostEntityMapper;
	@Resource
	private ErpQtnCostItemEntityMapper erpQtnCostItemEntityMapper;
	@Resource
	private SysUserEntityMapper sysUserEntityMapper;

	private static final Logger log = LoggerFactory
			.getLogger(ErpQuotationController.class);

	@SysLog("保存报价表头信息")
	@RequestMapping("/head/save")
	@RequiresPermissions("erp:quotation:head:save")
	public R headSave(@RequestBody Map<String, Object> params) {
		R r = new R();

//		System.out.println(params);
		ErpQuotationEntity erpQuotationEntity = BeanUtil.toBean(params,
				ErpQuotationEntity.class);

		SysUserEntity sysUser = ShiroUtils.getUserEntity();
		erpQuotationEntity.setQuotationNo(getQuotationNo(sysUser));
		erpQuotationEntity.setStatus(1);
		erpQuotationEntity.setUserName(sysUser.getUsername());
		erpQuotationEntity.setTrueName(sysUser.getTruename());
		erpQuotationEntity.setDepartment(sysUser.getDepartment());
		erpQuotationEntity.setCreateTime(new Date());

		// Integer i = erpQuotationService.saveHead(erpQuotationEntity);
		// Integer i = erpQuotationEntityMapper.insert(erpQuotationEntity);
		/* mybatis-plus activeRecord 模式 */
		Boolean b = erpQuotationEntity.insert();

		if (b) {
			UpdateWrapper<SysUserEntity> uw = new UpdateWrapper<SysUserEntity>();
			SysUserEntity user = new SysUserEntity();
			user.setFlowNo(sysUser.getFlowNo() + 1);
			uw.eq("areaCode", sysUser.getAreaCode());
			sysUserEntityMapper.update(user, uw);
			sysUser.setFlowNo(sysUser.getFlowNo() + 1);

			r.put("code", 200);
			r.put("tableHead", erpQuotationEntity);
		} else {
			r.put("code", 250);
		}
//		}

		return r;

	}

	@SysLog("修改报价表头信息")
	@RequestMapping("/head/update")
	@RequiresPermissions("erp:quotation:head:update")
	public R headUpdate(@RequestBody Map<String, Object> params) {
		R r = new R();
		ErpQuotationEntity erpQuotationEntity = BeanUtil.toBean(params,
				ErpQuotationEntity.class);
		erpQuotationEntity.setID((Integer) params.get("id"));

//		UpdateWrapper<ErpQuotationEntity> ur = new UpdateWrapper<ErpQuotationEntity>();
//		ur.eq("ID", params.get("quotationNo"));
		Integer i = erpQuotationEntityMapper.updateById(erpQuotationEntity);
		if (i > 0)
			r.put("code", 200);
		else
			r.put("code", 250);
		return r;

	}

	/*
	 * 按ID获取报价单
	 */
	@SysLog("按ID查询报价头")
	@RequestMapping("/head/queryID")
	@RequiresPermissions("erp:quotation:head:queryID")
	public @ResponseBody R headList(@RequestBody JSONObject prams) {
		R r = new R();
//		QueryWrapper<ErpQuotationEntity> queryWrapper = new QueryWrapper<ErpQuotationEntity>();
//		queryWrapper.eq("ID", prams.getInteger("id"));		
		ErpQuotationEntity qtn = erpQuotationEntityMapper
				.selectById(prams.getInteger("id"));

		Map<String, Object> map = erpQtnProductCostEntityMapper
				.total(prams.getInteger("id"));
		r.put("headWinData", qtn);
		r.put("total", (BigDecimal) map.get("total"));
		r.put("code", 200);
		return r;
	}

	/*
	 * 按用户权限获取报价单列表
	 */
	@SysLog("报价列表查询")
	@RequestMapping("/list")
	@RequiresPermissions("erp:quotation:list")
	public @ResponseBody R list(@RequestBody JSONObject prams) {
		R r = new R();
		SysUserEntity user = ShiroUtils.getUserEntity();
		QueryWrapper<ErpQuotationEntity> queryWrapper = new QueryWrapper<ErpQuotationEntity>();
		Map<String, Object> map = new LinkedMap<String, Object>();
		map.put("department", user.getDepartment());
		map.put("trueName", user.getTruename());

		switch (user.getPower()) {
		case 3:
			break;
		case 2:
			queryWrapper.eq("department", user.getDepartment());
			break;
		case 1:
			queryWrapper.eq("trueName", user.getTruename());
			break;
		default:
			queryWrapper.eq("trueName", user.getTruename());
			break;
		}
		queryWrapper.like("quotationNo", prams.getString("quotationNo"))
				.like("CardName", prams.getString("cardName"));
		queryWrapper.orderByDesc("id");
		List<ErpQuotationEntity> listQtnEntity = erpQuotationEntityMapper
				.selectList(queryWrapper);

		r.put("tableData", listQtnEntity);
		r.put("code", 200);
		return r;
	}

	@SysLog("保存报价产品")
	@RequestMapping("/product/save")
	@RequiresPermissions("erp:quotation:product:save")
	public @ResponseBody R productSave(@RequestBody JSONObject prams) {
		R r = new R();
		QueryWrapper<ErpQtnProductEntity> queryWrapper = new QueryWrapper<ErpQtnProductEntity>();
		// queryWrapper.eq("QuotationID", prams.getInteger("quotationID"));
		ErpQtnProductEntity erpQtnProductEntity = BeanUtil.toBean(prams,
				ErpQtnProductEntity.class);

		Integer i = erpQtnProductEntityMapper.insert(erpQtnProductEntity);
		queryWrapper.eq("quotationID", prams.getInteger("quotationID"));
		List<ErpQtnProductEntity> lstQtnProduct = erpQtnProductEntityMapper
				.selectList(queryWrapper);

		if (i > 0) {
			r.put("prodLines", lstQtnProduct);
			r.put("code", 200);
		} else {
			lstQtnProduct = null;
			r.put("prodLines", lstQtnProduct);
			r.put("code", 500);
		}
		return r;
	}

	@SysLog("删除报价产品")
	@RequestMapping("/product/delete")
	@RequiresPermissions("erp:quotation:product:delete")
	public @ResponseBody R productDelete(@RequestBody JSONObject prams) {
		R r = new R();
		QueryWrapper<ErpQtnProductEntity> queryWrapper = new QueryWrapper<ErpQtnProductEntity>();

		Integer i = erpQtnProductEntityMapper
				.deleteById(prams.getInteger("productID"));
		queryWrapper.eq("quotationID", prams.getInteger("quotationID"));
		List<ErpQtnProductEntity> lstQtnProduct = erpQtnProductEntityMapper
				.selectList(queryWrapper);

		if (i > 0) {
			r.put("prodLines", lstQtnProduct);
			r.put("code", 200);
		}
		return r;
	}

	@SysLog("报价产品更新")
	@RequestMapping("/product/update")
	@RequiresPermissions("erp:quotation:product:update")
	public @ResponseBody R productUpdate(@RequestBody JSONObject prams) {
		R r = new R();
		QueryWrapper<ErpQtnProductEntity> queryWrapper = new QueryWrapper<ErpQtnProductEntity>();
		ErpQtnProductEntity erpQtnProductEntity = BeanUtil.toBean(prams,
				ErpQtnProductEntity.class);
		Integer i = erpQtnProductEntityMapper.updateById(erpQtnProductEntity);
		queryWrapper.eq("quotationID", prams.getInteger("quotationID"));

		List<ErpQtnProductEntity> lstQtnProduct = erpQtnProductEntityMapper
				.selectList(queryWrapper);

		if (i > 0) {
			r.put("prodLines", lstQtnProduct);
			r.put("code", 200);
		}
		return r;
	}

	@SysLog("查询报价产品列表")
	@RequestMapping("/product/list")
	@RequiresPermissions("erp:quotation:product:list")
	public @ResponseBody R productList(@RequestBody JSONObject prams) {
		R r = new R();
		QueryWrapper<ErpQtnProductEntity> queryWrapper = new QueryWrapper<ErpQtnProductEntity>();
		queryWrapper.eq("QuotationID", prams.getInteger("quotationID"));

		if (prams.getInteger("all") == 0) {
			queryWrapper.isNotNull("confirmName");

		}

		List<ErpQtnProductEntity> lstQtnProduct = erpQtnProductEntityMapper
				.selectList(queryWrapper);
		r.put("productList", lstQtnProduct);
		r.put("prodLines", lstQtnProduct);
		r.put("code", 200);
		return r;
	}

	// @SysLog("上传报价附件")
	@RequestMapping("/attach/upload")
	@RequiresPermissions("erp:quotation:attach:upload")
	public @ResponseBody R attachUpload(
			@RequestParam("file") MultipartFile file,
			@RequestParam("quotationNo") String quotationNo,
			@RequestParam("quotationID") Integer quotationID) {
		R r = new R();
		String url = "D:\\quotation\\" + quotationNo;
		Boolean b = UploadFile.saveUpload(file, url);

		if (b) {
			r.put("code", 2);
			ErpQtnAttachEntity erpQtnAttachEntity = new ErpQtnAttachEntity();
			SysUserEntity user = ShiroUtils.getUserEntity();
			erpQtnAttachEntity.setQuotationID(quotationID);
			erpQtnAttachEntity.setUserName(user.getUsername());
			erpQtnAttachEntity.setTrueName(user.getTruename());
			erpQtnAttachEntity.setFileName(file.getOriginalFilename());
			erpQtnAttachEntity.setUrl("d:\\quotation\\" + quotationNo + "\\"
					+ file.getOriginalFilename());
			erpQtnAttachEntity.setTransTime(new Date());
			QueryWrapper<ErpQtnAttachEntity> queryWrapper = new QueryWrapper<ErpQtnAttachEntity>();
			int i = erpQtnAttachEntityMapper.insert(erpQtnAttachEntity);
			queryWrapper.eq("quotationID", quotationID);
			List<ErpQtnAttachEntity> lstAttach = erpQtnAttachEntityMapper
					.selectList(queryWrapper);
			r.put("record", i);
			r.put("attachLines", lstAttach);
		} else {
			r.put("code", 250);
		}
		return r;
	}

	// @SysLog("查询报价附件列表")
	@RequestMapping("/attach/list")
	@RequiresPermissions("erp:quotation:attach:list")
	public @ResponseBody R attachList(@RequestBody JSONObject prams) {
		R r = new R();
		QueryWrapper<ErpQtnAttachEntity> queryWrapper = new QueryWrapper<ErpQtnAttachEntity>();
		queryWrapper.eq("QuotationID", prams.getInteger("quotationID"));

		List<ErpQtnAttachEntity> lstQtnAttach = erpQtnAttachEntityMapper
				.selectList(queryWrapper);
		r.put("attachLines", lstQtnAttach);
		r.put("code", 200);
		return r;
	}

	// @SysLog("下载报价附件")
	@RequestMapping("/attach/download")
	// @RequiresPermissions("erp:quotation:attach:list")
	public ResponseEntity<FileSystemResource> attachDownload(
			@RequestBody JSONObject prams) {
		String url = prams.getString("url");
		String fileName = prams.getString("fileName");
		File file = new File(url);

		if (file.exists()) {
			HttpHeaders headers = new HttpHeaders();
			headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
			headers.add("Content-Disposition",
					"attachment; filename=" + file.getName());
			headers.add("Pragma", "no-cache");
			headers.add("Expires", "0");
			headers.add("Last-Modified", new Date().toString());
			headers.add("ETag", String.valueOf(System.currentTimeMillis()));
			return ResponseEntity.ok().headers(headers)
					.contentLength(file.length())
					.contentType(MediaType
							.parseMediaType("application/octet-stream"))
					.body(new FileSystemResource(file));

		} else

			return null;
	}

	@SysLog("保存报价产品成本信息")
	@RequestMapping("/prodCost/save")
	@RequiresPermissions("erp:quotation:prodCost:save")
	public @ResponseBody R prodCostSave(@RequestBody JSONObject prams) {
		R r = new R();
		QueryWrapper<ErpQtnProductCostEntity> queryWrapper = new QueryWrapper<ErpQtnProductCostEntity>();
		queryWrapper.eq("QuotationID", prams.getInteger("quotationID"));
		SysUserEntity user = ShiroUtils.getUserEntity();
		ErpQtnProductCostEntity erpQtnProductCostEntity = BeanUtil.toBean(prams,
				ErpQtnProductCostEntity.class);
		BigDecimal qty = BigDecimal.valueOf(prams.getInteger("quantity"));
		BigDecimal price = prams.getBigDecimal("costPrice");
		BigDecimal amt = price.multiply(qty);
		erpQtnProductCostEntity.setCostAmount(amt);
		erpQtnProductCostEntity.setUserName(user.getUsername());
		erpQtnProductCostEntity.setTrueName(user.getTruename());
		erpQtnProductCostEntity.setCostType("按产品");
		erpQtnProductCostEntity.setCreateTime(new Date());

		int i = erpQtnProductCostEntityMapper.insert(erpQtnProductCostEntity);
		/*
		 * 以下为获取
		 */
		queryWrapper.select("sum(costAmount) as total");
		Map<String, Object> map = erpQtnProdCostService.getMap(queryWrapper);
		BigDecimal total = BigDecimal
				.valueOf(Double.valueOf(map.get("total").toString()));
		queryWrapper.clear();

		r.put("record", i);
		r.put("total", total);
		r.put("code", 200);
		return r;
	}

	@SysLog("删除报价产品成本行")
	@RequestMapping("/prodCost/delete")
	@RequiresPermissions("erp:quotation:prodCost:delete")
	public @ResponseBody R prodCostDelete(@RequestBody JSONObject prams) {
		R r = new R();
		erpQtnProductCostEntityMapper
				.deleteById(prams.getInteger("prodCostID"));
		r.put("code", 200);
		return r;
	}

	@SysLog("查询报价产品成本列表")
	@RequestMapping("/prodCost/list")
	@RequiresPermissions("erp:quotation:prodCost:list")
	public @ResponseBody R prodCostList(@RequestBody JSONObject prams) {
		R r = new R();
		QueryWrapper<ErpQtnProductCostEntity> queryWrapper = new QueryWrapper<ErpQtnProductCostEntity>();
		queryWrapper.eq("QuotationID", prams.getInteger("quotationID"));
		List<ErpQtnProductCostEntity> lstProdCost = erpQtnProductCostEntityMapper
				.selectList(queryWrapper);
		r.put("prodCostLines", lstProdCost);
		r.put("code", 200);
		return r;
	}

	@SysLog("查询报价成本项目列表")
	@RequestMapping("/costItem/list")
	@RequiresPermissions("erp:quotation:costItem:list")
	public @ResponseBody R costItemList(@RequestBody JSONObject prams) {
		R r = new R();
		QueryWrapper<ErpQtnCostItemEntity> qr = new QueryWrapper<ErpQtnCostItemEntity>();
		List<ErpQtnCostItemEntity> lstCostItem = erpQtnCostItemEntityMapper
				.selectList(qr);
		r.put("costItemList", lstCostItem);
		r.put("code", 200);
		return r;
	}

	@SysLog("updateQtnStatus")
	@RequestMapping("/updateQtnStatus")
	public void updateQtnStatus(Integer quotationID, String department) {
		UpdateWrapper<ErpQuotationEntity> updateWrapper = new UpdateWrapper<ErpQuotationEntity>();
		updateWrapper.eq("quotationID", quotationID);
		ErpQuotationEntity qtn = erpQuotationEntityMapper
				.selectById(quotationID);
		switch (department) {
		case "技术中心":
			qtn.setStatus(2);
			break;
		case "财务部":
			qtn.setStatus(3);
			break;
		default:
			qtn.setStatus(1);
			break;
		}
		erpQuotationEntityMapper.update(qtn, updateWrapper);

	}

	@SysLog("updateQtnStatus2")
	@RequestMapping("/updateQtnStatus2")
	public void updateQtnStatus(Integer quotationID, Integer status) {
		UpdateWrapper<ErpQuotationEntity> updateWrapper = new UpdateWrapper<ErpQuotationEntity>();
		updateWrapper.eq("quotationID", quotationID);
		ErpQuotationEntity qtn = erpQuotationEntityMapper
				.selectById(quotationID);
		qtn.setStatus(status);
		erpQuotationEntityMapper.update(qtn, updateWrapper);

	}

	@SysLog("getQuotationNo")
	@RequestMapping("/getQuotationNo")
	public String getQuotationNo(SysUserEntity user) {
		String qtnNo = "";
		Integer flowNo = user.getFlowNo() + 1;
		String areaCode = user.getAreaCode();
		SimpleDateFormat sdf = new SimpleDateFormat("yy");
		Date date = new Date();

		qtnNo = "JB" + sdf.format(date) + areaCode
				+ String.format("%03d", flowNo);

		return qtnNo;

	}

}
